#!/usr/bin/env node

/**
 * Web Monitor SDK 发布脚本
 * 这个脚本会创建一个独立的npm包，不影响现有项目
 */

const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

const PROJECT_ROOT = path.resolve(__dirname, '..')
const MONITOR_SOURCE = path.join(PROJECT_ROOT, 'utils/monitor')
const NPM_PACKAGE_DIR = path.join(PROJECT_ROOT, 'npm-package')

console.log('🚀 开始发布 Web Monitor SDK 到 npm...')

// 1. 确保npm-package目录存在
if (!fs.existsSync(NPM_PACKAGE_DIR)) {
  fs.mkdirSync(NPM_PACKAGE_DIR)
  console.log('✅ 创建 npm-package 目录')
}

// 2. 复制源代码（排除不需要的文件）
console.log('📦 复制源代码文件...')

const filesToCopy = [
  'index.ts',
  'WebMonitorSDK.ts', 
  'MonitorTypes.ts',
  'collectors/',
  'core/',
  'reporter/',
  'utils/',
  'INTEGRATION.md'
]

filesToCopy.forEach(file => {
  const sourcePath = path.join(MONITOR_SOURCE, file)
  const targetPath = path.join(NPM_PACKAGE_DIR, file)
  
  if (fs.existsSync(sourcePath)) {
    if (fs.statSync(sourcePath).isDirectory()) {
      // 复制目录
      copyDirectory(sourcePath, targetPath)
    } else {
      // 复制文件
      fs.copyFileSync(sourcePath, targetPath)
    }
    console.log(`  ✅ ${file}`)
  } else {
    console.log(`  ⚠️ ${file} 不存在，跳过`)
  }
})

// 3. 创建npm包配置文件
console.log('⚙️ 创建npm包配置文件...')

const packageJson = {
  "name": "web-monitor-sdk",
  "version": "1.0.0",
  "description": "企业级前端监控SDK，支持错误监控、性能追踪、网络监控和用户行为分析",
  "main": "dist/index.js",
  "module": "dist/index.esm.js",
  "types": "dist/index.d.ts",
  "files": [
    "dist",
    "README.md",
    "INTEGRATION.md"
  ],
  "scripts": {
    "build": "rollup -c",
    "build:prod": "rollup -c --environment NODE_ENV:production",
    "prepublishOnly": "npm run build"
  },
  "keywords": [
    "monitor", "monitoring", "frontend", "error-tracking", 
    "performance", "analytics", "web-vitals", "typescript",
    "vue", "react", "uni-app", "小程序", "h5", "app"
  ],
  "author": {
    "name": "MyApp Team",
    "email": "team@myapp.com"
  },
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/myapp/web-monitor-sdk.git"
  },
  "engines": {
    "node": ">=14.0.0"
  },
  "peerDependencies": {
    "vue": ">=3.0.0"
  },
  "peerDependenciesMeta": {
    "vue": {
      "optional": true
    }
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^25.0.0",
    "@rollup/plugin-node-resolve": "^15.0.0",
    "@rollup/plugin-typescript": "^11.0.0",
    "rollup": "^3.0.0",
    "rollup-plugin-dts": "^6.0.0",
    "rollup-plugin-terser": "^7.0.0",
    "typescript": "^5.0.0"
  }
}

fs.writeFileSync(
  path.join(NPM_PACKAGE_DIR, 'package.json'),
  JSON.stringify(packageJson, null, 2)
)

// 4. 创建Rollup配置
const rollupConfig = `import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from '@rollup/plugin-typescript'
import { terser } from 'rollup-plugin-terser'
import dts from 'rollup-plugin-dts'

const isProduction = process.env.NODE_ENV === 'production'

const baseConfig = {
  input: 'index.ts',
  external: ['vue'],
  plugins: [
    resolve({ browser: true, preferBuiltins: false }),
    commonjs(),
    typescript({ declaration: false, declarationMap: false })
  ]
}

export default [
  // ES Module
  {
    ...baseConfig,
    output: { file: 'dist/index.esm.js', format: 'es', sourcemap: true },
    plugins: [...baseConfig.plugins, ...(isProduction ? [terser()] : [])]
  },
  // CommonJS
  {
    ...baseConfig,
    output: { file: 'dist/index.js', format: 'cjs', sourcemap: true, exports: 'auto' },
    plugins: [...baseConfig.plugins, ...(isProduction ? [terser()] : [])]
  },
  // UMD
  {
    ...baseConfig,
    output: { 
      file: 'dist/index.umd.js', 
      format: 'umd', 
      name: 'WebMonitorSDK', 
      sourcemap: true,
      globals: { vue: 'Vue' }
    },
    plugins: [...baseConfig.plugins, ...(isProduction ? [terser()] : [])]
  },
  // TypeScript declarations
  {
    input: 'index.ts',
    output: { file: 'dist/index.d.ts', format: 'es' },
    plugins: [dts()],
    external: ['vue']
  }
]`

fs.writeFileSync(path.join(NPM_PACKAGE_DIR, 'rollup.config.js'), rollupConfig)

// 5. 创建TypeScript配置
const tsConfig = {
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext", 
    "lib": ["ES2018", "DOM", "DOM.Iterable"],
    "declaration": true,
    "outDir": "./dist",
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

fs.writeFileSync(
  path.join(NPM_PACKAGE_DIR, 'tsconfig.json'),
  JSON.stringify(tsConfig, null, 2)
)

console.log('✅ npm包文件准备完成！')
console.log('📁 包目录:', NPM_PACKAGE_DIR)
console.log('')
console.log('🔥 接下来的步骤:')
console.log('1. cd npm-package')
console.log('2. npm install')
console.log('3. npm run build')
console.log('4. npm publish')
console.log('')
console.log('⚠️ 注意: 这个npm包完全独立，不会影响您的现有项目!')

// 辅助函数：递归复制目录
function copyDirectory(src, dest) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true })
  }
  
  const files = fs.readdirSync(src)
  
  files.forEach(file => {
    const srcPath = path.join(src, file)
    const destPath = path.join(dest, file)
    
    if (fs.statSync(srcPath).isDirectory()) {
      copyDirectory(srcPath, destPath)
    } else {
      fs.copyFileSync(srcPath, destPath)
    }
  })
} 